<template>
  <div class="app-container">
    <el-form :model="formData" label-width="120px" label-position="left">
      <el-form-item label="专业名称">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="专业分类">
          <el-select filterable v-model="formData.categoryId" placeholder="请选择专业分类">
            <el-option
              v-for="item in categoryList"
              :key="item.majorCategoryId"
              :label="item.majorCategoryName"
              :value="item.majorCategoryId">
            </el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="专业介绍">
        <Tinymce v-model="formData.desc" :height="400" />
      </el-form-item>
    </el-form>
    <div class="submit-box">
      <el-button type="primary" :loading="loading" style="width: 200px;" @click.native.prevent="doSubmit">提交</el-button>
    </div>
  </div>
</template>

<script>
  import Tinymce from '@/components/Tinymce'
  import { edit, getDetail } from '@/api/major'
  import { getSecond } from '@/api/major_category'
  import { errorMsg, successMsg } from '@/utils/my'

  export default {
    components: { Tinymce },
    data() {
      return {
        loading: false,
        formData: {
          id: 0,
          name: '',
          categoryId: '',
          desc: ''
        },
        categoryList: []
      }
    },

    created() {
      this.formData.id = this.$route.params.id
      this.fetchSecondCategoryList()
      this.fetchData()
    },

    methods: {
      fetchData() {
        let that = this
        getDetail({id: that.formData.id}).then(res => {
          that.formData.categoryId = res.data.majorCategoryId
          that.formData.name = res.data.majorName
          that.formData.desc = res.data.majorDesc
        })
      },

      doSubmit() {
        let that = this,
            d = that.formData
        if (d.name.length <= 0) {
          return errorMsg('请输入专业名称')
        }
        if (d.categoryId.length <= 0) {
          return errorMsg('请选择专业分类')
        }
        that.loading = true
        edit(that.formData).then(res => {
          that.loading = false
          if (res.code != 20000) {
            return errorMsg(res.message)
          }
          successMsg(res.message)
          setTimeout(function() {
            that.$router.push({path: '/admin/major'})
          }, 1500)
        })
      },

      fetchSecondCategoryList() {
        const that = this
        getSecond().then(res => {
          that.categoryList = res.data
        })
      }
    }
  }
</script>

<style>
  .submit-box {
    height: 50px;
    line-height: 50px;
    text-align: center;
    padding-right: 20px;
  }
</style>
